package controller

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"store/libs/helper"
	"store/logic"
)

type Common struct {
	Controller
	Logic logic.RestLogic
}

func (this *Common) Post(ctx *gin.Context) {
	logic4Ctx := this.Logic.Clone(ctx)
	input, err := logic4Ctx.LoadInput()
	if err != nil {
		this.Response(ctx, http.StatusBadRequest, this.FormatError(input, err).Error(), nil)
		return
	}

	id := logic4Ctx.Add(&input)
	if id < 1 {
		this.Response(ctx, http.StatusInternalServerError, "添加失败", nil)
		return
	}

	info, _ := logic4Ctx.View(map[string]interface{}{
		"id": id,
	})
	this.Response(ctx, http.StatusOK, "ok", info)
	return
}

func (this *Common) Delete(ctx *gin.Context) {
	id, err := this.GetInfoParams(ctx)
	if err != nil {
		this.Response(ctx, http.StatusBadRequest, err.Error(), nil)
		return
	}

	rId := helper.ToInt(id)
	if rId < 0 {
		this.Response(ctx, http.StatusBadRequest, "id最小为1", nil)
		return
	}

	this.Logic.Clone(ctx).Delete(uint64(rId))

	this.Response(ctx, http.StatusOK, "ok", nil)
}

func (this *Common) UpOrDown(ctx *gin.Context) {
	id, err := this.GetInfoParams(ctx)
	if err != nil {
		this.Response(ctx, http.StatusBadRequest, err.Error(), nil)
		return
	}

	rId := helper.ToInt(id)
	if rId < 0 {
		this.Response(ctx, http.StatusBadRequest, "id最小为1", nil)
		return
	}

	val, err := this.GetUpOrDownParams(ctx)
	if err != nil {
		this.Response(ctx, http.StatusBadRequest, err.Error(), nil)
		return
	}

	this.Logic.Clone(ctx).UpOrDown(uint64(rId), val)

	this.Response(ctx, http.StatusOK, "ok", nil)
}

func (this *Common) Put(ctx *gin.Context) {
	id, err := this.GetInfoParams(ctx)
	if err != nil {
		this.Response(ctx, http.StatusBadRequest, err.Error(), nil)
		return
	}

	logic4Ctx := this.Logic.Clone(ctx)

	input, version, err := logic4Ctx.LoadInput4Update(map[string]interface{}{
		"id": id,
	})

	if err != nil {
		this.Response(ctx, http.StatusBadRequest, this.FormatError(input, err).Error(), nil)
		return
	}

	logic4Ctx.Update(version, input)
	info, _ := logic4Ctx.View(map[string]interface{}{
		"id": id,
	})

	this.Response(ctx, http.StatusOK, "ok", info)
}

func (this *Common) Get(ctx *gin.Context) {
	id, err := this.GetInfoParams(ctx)

	if err != nil {
		this.Response(ctx, http.StatusBadRequest, err.Error(), nil)
		return
	}

	info, exists := this.Logic.Clone(ctx).View(map[string]interface{}{
		"id": id,
	})

	if !exists {
		this.Response(ctx, http.StatusNotFound, "not found", nil)
		return
	}

	this.Response(ctx, http.StatusOK, "ok", info)
}

func (this *Common) GetIndex(ctx *gin.Context) {
	page, pageSize, where, orders := this.GetIndexParams(ctx)
	result := this.Logic.Clone(ctx).Index(page, pageSize, where, orders)

	this.Response(ctx, http.StatusOK, "ok", result)
}
